package com.dscyy.readutil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class CreateHotdata implements Runnable{
	
	static List<String[]> allShop = new ArrayList<String[]>();
	static List<String[]> allCurs = new ArrayList<String[]>();
	static List<String[]> allLimit = new ArrayList<String[]>();
	static DecimalFormat df = new DecimalFormat("#.00");
	static SimpleDateFormat nowformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	static SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd");
	static SimpleDateFormat hour = new SimpleDateFormat("HH");
	
	static Map<Integer, HourLimitPercentage> limitHour = new HashMap<Integer, HourLimitPercentage>();
	
	public static void main(String[] args) throws Exception {
		CreateHotdata ch = new CreateHotdata();
		Thread thread = new Thread(ch);
		thread.start();
	}
	
	private static boolean notFullOfLimit(int size, String hour) {
		HourLimitPercentage hourlimit = limitHour.get(Integer.parseInt(hour));
		hourlimit.setNums(hourlimit.getNums()+size);
		if(hourlimit.getLimitNums() > hourlimit.getNums()) {
			return true;
		}
		return false;
	}

	private static void commitSqlToDB(List<String> sqls) throws Exception {
		Class.forName("com.mysql.cj.jdbc.Driver");
		//Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dscyy?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "dscyy", "KeJ5AdNjmfrpMtba");
		Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hdview?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=true", "hdview", "nmwWS74fJKmGf23z");
//		Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dscyy?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC", "root", "");
		Statement stmt = conn.createStatement();
		for(String sql : sqls) {
			stmt.addBatch(sql);
		}
		stmt.executeBatch();
		stmt.close();
		conn.close();
	}

	private static List<String[]> readLimit() throws Exception {
		// 读取用户数据
		String filename = "数量限制.csv";
		String regex = ",";
		return readFiles(filename, regex);
	}

	private static List<String[]> readShop() throws Exception{
		// 读取用户数据
		String filename = "商品信息.csv";
		String regex = ",";
		return readFiles(filename, regex);
	}
	
	private static List<String[]> readAreas() throws Exception{
		// 读取用户数据
		String filename = "地区.csv";
		String regex = ",";
		return readFiles(filename, regex);
	}	

	private static List<String[]> readFiles(String filename, String regex) throws Exception {
		List<String[]> lineList = new ArrayList<String[]>();
		InputStreamReader isr = new InputStreamReader(new FileInputStream(filename), "GB2312"); // 或GB2312,GB18030
		BufferedReader read = new BufferedReader(isr);
		String contentLine = read.readLine();
		while (contentLine != null) {
			lineList.add(contentLine.split(regex));
			contentLine = read.readLine();
		}
		read.close();
		isr.close();
		return lineList;
	}

	@Override
	public void run() {

		try {
			allShop = readShop();// 全部店铺及商品
			allCurs = readAreas();// 读取地区
			allLimit = readLimit();// 读取记录数量限制
			initLimitHour();
			String today = dformat.format(new Date());
			int count = 1;
			while(true) {
				int sleep = 10;
				List<String> allSql = new ArrayList<String>();
				int records = Integer.parseInt(Math.round(Math.random() * 10)+"");
				String nowhour = hour.format(new Date());
				if(limitHour.get(Integer.parseInt(nowhour)).getLimitNums()>=720) {
					records = (int) Math.ceil(limitHour.get(Integer.parseInt(nowhour)).getLimitNums()*1.0/720);
					sleep = 5;
				}else {
					records = 1;
					sleep = (Math.round(720/limitHour.get(Integer.parseInt(nowhour)).getLimitNums())+1) * 10;
				}
				for(int i=0;i<records;i++) {
					int fromIndex = Integer.parseInt(Math.round(Math.random() * (allShop.size()-1))+"");
					String[] shop = allShop.get(fromIndex);
					String orderid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
					String platform = shop[0];
					String shopname = shop[2];
					String productname = shop[3];
					String tradetime = nowformat.format(new Date());
					String[] tradearea = allCurs.get(Integer.parseInt(Math.round(Math.random()*(allCurs.size()-2))+""));
					//Long nums = Math.round(Math.random()*4);
					int nums = 1;
					double tradeamount = (nums==0?1:nums) * (Double.parseDouble(shop[4]));
					tradeamount = Double.parseDouble(df.format(tradeamount));
					String sex = "女";
					long age = Math.round(Math.random()*70);
					if(Integer.parseInt(nowhour) >= 13 && age > 38) {
						sex = Math.round(Math.random()*100)%2==0?"男":"女";
					}else {
						sex = Math.round(Math.random()*100)%3==0?"男":"女";
					}
					String category = shop[1];
					String clients = Math.round(Math.random()*100) / 95.16 < 1 ? "1" : "2"; // 1-无线 2-PC
					String sql = "insert into hot_data_info(orderid,platform,shop,productname,tradetime,tradearea,tradeamount,sex,age,category,clients) values('"+
					orderid+"','"+platform+"','"+shopname+"','"+productname+"','"+tradetime+"','"+tradearea[0]+"',"+tradeamount+",'"+sex+"',"+age+",'"+category+"','"+clients+"')";
					allSql.add(sql);
				}
				if(!today.equals(dformat.format(new Date()))){
					long from =  Runtime.getRuntime().freeMemory();;
					Runtime.getRuntime().gc();
					long end = Runtime.getRuntime().freeMemory();
					System.out.println("=============隔天清理内存=====================");
					System.out.println(nowformat.format(new Date()) + " 清理内存 ：" + (end - from)/1024/1024 + " M");
					today = dformat.format(new Date());
					initLimitHour();
				}
				// 执行脚本
				if(notFullOfLimit(allSql.size(), nowhour)) {
					commitSqlToDB(allSql);
					System.out.println(nowformat.format(new Date()) + " 同步数据成功！");
				}else {
					commitSqlToDB(allSql.subList(0, 1));
					System.out.println(nowformat.format(new Date()) + " 同步数据成功！");
				}
				Thread.sleep(sleep * 1000);
				if(count++ > 1000) {
					count = 0;
					long from =  Runtime.getRuntime().freeMemory();;
					Runtime.getRuntime().gc();
					long end = Runtime.getRuntime().freeMemory();
					System.out.println(nowformat.format(new Date()) + " 清理内存 ：" + (end - from)/1024/1024 + " M");
				}
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		
	}

	private void initLimitHour() {
		for(String[] limt : allLimit) {
			HourLimitPercentage hour = new HourLimitPercentage();
			hour.setHour(Integer.parseInt(limt[0]));
			hour.setLimitNums(Integer.parseInt(limt[1]));
			hour.setNums(0);
			limitHour.put(hour.getHour(), hour);
		}		
	}


}
